package com.project.springboot.ssedemo;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 参考：<a href="https://blog.csdn.net/boydoy1987/article/details/141133592">...</a>
 * description: sse小样儿控制器
 * @author 朱正磊
 * @date 2025-10-16 16:58:53
 */
@Controller
@RequestMapping("/sse/demo")
public class SseDemoController {

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * description: 跳转到sse小样儿页面
     * @author 朱正磊
     * @date 2025-10-16 17:30:15
     * @return 返回逻辑视图地址
     */
    @GetMapping("/toSseDemo")
    public String toSseDemo() {
        return "sse/sseDemo";
    }

    /**
     * description: sse服务器端服务
     * @author 朱正磊
     * @date 2025-10-16 17:20:17
     * @return 返回sse发射器
     */
    @GetMapping(value = "/streamSseMvc", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamSseMvc() {
        SseEmitter emitter = new SseEmitter();
        executorService.execute(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(1000);
                    emitter.send("message" + i);
                }
                emitter.complete();
            } catch (InterruptedException | IOException e) {
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }

}
